package com.imooc.spark

import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * Created by zghgchao 2017/11/17 9:34
  * Spark Streaming对接Kafka的方式-- Receiver-based Approach
  */
object KafkaReceiverWordCount {
  def main(args: Array[String]): Unit = {

    if (args.length != 4) {
      System.err.println("Usage：KafkaReceiverWordCount <zkQuorum> <group> <topics> <numThreads>")
      System.exit(1)
    }

    val Array(zkQuorum, group, topics, numThreads) = args

    val sparkConf = new SparkConf().setAppName("KafkaReceiverWordCount").setMaster("local[2]")
    val ssc = new StreamingContext(sparkConf, Seconds(5))

    val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap
    //TODO... Receiver-based Approach
    val messages = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap)

//    messages.print()  //(null,a a a a d d d s s s)
    messages.map(_._2).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_ + _).print()

    ssc.start()
    ssc.awaitTermination()
  }
}
